
import path from 'path'
import fs from 'fs-extra'
import inquirer from 'inquirer'
import ini from 'ini'
import _ from 'lodash'
import ora from 'ora'
import { GMC_CONF, GMC_PATH, GMC_CONFILE, getProjectList } from './base'

export default () => {
  let options = null
  return inquirer.prompt([
    {
      type: 'list',
      name: 'option',
      message: '项目配置选项 ?',
      choices: [
        {
          key: '0',
          name: '1) 创建项目配置',
          value: 'create'
        },
        {
          key: '1',
          name: '2) 修改项目配置',
          value: 'edit'
        },
        {
          key: '2',
          name: '3) 删除项目配置',
          value: 'remove'
        },
      ]
    }
  ])
  .then( ret => {
    switch (ret.option) {
      case 'create': {
        return addProject()
      }
      case 'edit': {
        return editProject()
      }
      case 'remove': {
        return removeProject()
      }
      default:
        break
    }
  })
}

const addProject = () => {
  let options = null
  return inquirer.prompt([
    {
      type: 'input',
      name: 'project',
      message: '项目标志 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '项目标志不能为空 !'
        }
        if (!/[0-9a-zA-Z\-\_]/.test(value)) {
          return '项目标志格式错误，必须是数字、英文字母或下划线组成 !'
        }
        if (_.has(GMC_CONF, value)) {
          return '项目标志已存在，此项不能重名 !'
        }
        return true
      }
    },
    {
      type: 'input',
      name: 'name',
      message: '项目名称 ?',
      validate: value => {
        if (_.isEmpty(_.trim(value))) {
          return '项目名称不能为空 !'
        }
        if (!/[0-9a-zA-Z\-\_\u4e00-\u9fa5]/.test(value)) {
          return '项目名称格式错误，必须是数字、英文字母、下划线或中文组成 !'
        }
        return true
      }
    }
  ])
  .then( ret => {
    options = { ...options, ...ret }
    return inquirer.prompt([
      {
        type: 'input',
        name: 'path',
        message: '项目路径名称 ?',
        default: options.project,
        validate: value => {
          if (_.isEmpty(_.trim(value))) {
            return '项目路径名称不能为空 !'
          }
          if (!/[0-9a-zA-Z\-\_]/.test(value)) {
            return '项目路径名称格式错误，必须是数字、英文字母或下划线组成 !'
          }
          if (fs.existsSync(path.resolve(GMC_PATH, value))) {
            return '项目路径已存在，请重填 !'
          }
          return true
        }
      },
      {
        type: 'input',
        name: 'proto',
        message: 'protobuf 接口文件',
        default: 'socket.proto'
      },
      {
        type: 'input',
        name: 'gmPB',
        message: 'protobuf GM文件',
        default: `gm.proto`
      },
      {
        type: 'input',
        name: 'prefix',
        message: 'protobuf 前缀',
        default: `com.${options.project}`
      }
    ])
  })
  .then( ret => {
    options = { ...options, ...ret }
    let newConf = {
      ...GMC_CONF,
      [options.project]: {
        ..._.omit(options, ['project'])
      }
    }
    console.log('')
    let spinner = ora(`    Create Project Configure ...`).start()
    fs.writeFileSync(GMC_CONFILE, ini.stringify(newConf, { whitespace: true }), 'utf-8')
    !fs.existsSync(path.resolve(GMC_PATH, options.path)) && fs.mkdirpSync(path.resolve(GMC_PATH, options.path))
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete Create Project Configure !\n')
    }, 500)
  })

}

const editProject = () => {
  let project = null
  let projectList = getProjectList()
  if (projectList.length === 0) {
    console.log(`\n   还没有项目建立，先去创建一个 !\n`)
    return
  }
  return inquirer.prompt([
    {
      type: 'list',
      name: 'project',
      message: '选择一个项目 ?',
      choices: projectList
    }
  ])
  .then( ret => {
    project = ret.project.replace(/(\[)([a-zA-Z]+)(\])(\s)(\-){2}(\s)(\S+)/, '$2')
    let projectConf = GMC_CONF[project]
    return inquirer.prompt([
      {
        type: 'input',
        name: 'name',
        message: '项目名称 ?',
        default: projectConf.name,
        validate: value => {
          if (_.isEmpty(_.trim(value))) {
            return '项目名称不能为空 !'
          }
          if (!/[0-9a-zA-Z\-\_\u4e00-\u9fa5]/.test(value)) {
            return '项目名称格式错误，必须是数字、英文字母、下划线或中文组成 !'
          }
          return true
        }
      },
      {
        type: 'input',
        name: 'proto',
        message: 'protobuf 接口文件',
        default: projectConf.proto
      },
      {
        type: 'input',
        name: 'gmPB',
        message: 'protobuf GM文件',
        default: projectConf.gmPB
      },
      {
        type: 'input',
        name: 'prefix',
        message: 'protobuf 前缀',
        default: projectConf.prefix
      }
    ])
  })
  .then( ret => {
    let projectConf = GMC_CONF[project]
    let newConf = {
      ...GMC_CONF,
      [project]: {
        ...projectConf,
        ...ret
      }
    }
    console.log('')
    let spinner = ora(`    Edit Project Configure ...`).start()
    fs.writeFileSync(GMC_CONFILE, ini.stringify(newConf, { whitespace: true }), 'utf-8')
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Complete Edit Project Configure !\n')
    }, 500)
  })
}

const removeProject = () => {
  let projectList = getProjectList()
  if (projectList.length === 0) {
    console.log(`\n   还没有项目建立，先去创建一个 !\n`)
    return
  }
  return inquirer.prompt([
    {
      type: 'checkbox',
      name: 'project',
      message: '选择一个项目 ?',
      choices: projectList
    }
  ])
  .then( ret => {
    if (ret.project.length === 0) {
      console.log(`\n   您没有选择任何项目 !\n`)
      return
    }
    console.log('')
    let spinner = ora(`    Remove Project Configure ...`).start()
    let newConf = GMC_CONF
    for (let item of ret.project) {
      let project = item.replace(/(\[)([a-zA-Z]+)(\])(\s)(\-){2}(\s)(\S+)/, '$2')
      let projectConf = GMC_CONF[project]
      fs.removeSync(path.resolve(GMC_PATH, projectConf.path))
      _.unset(newConf, project)
    }
    fs.writeFileSync(GMC_CONFILE, ini.stringify(newConf, { whitespace: true }), 'utf-8')
    setTimeout(() => {
      spinner.stop()
      console.log('✔   Remove Edit Project Configure !\n')
    }, 500)
  })
}